﻿using System.Globalization;
using System.Windows.Data;

namespace DimensionsHelper.Client.Converters;

[ValueConversion(typeof(bool), typeof(GridLength))]
public class BooleanToGridLengthConverter : IValueConverter, IMultiValueConverter
{
    public bool IsReversed { get; set; }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        bool isAllTrue = true;

        foreach (object val in values)
        {
            if (val is not bool bln || bln == IsReversed)
            {
                isAllTrue = false;
                break;
            }
        }

        if (isAllTrue)
        {
            return parameter switch
            {
                double d => new GridLength(d),
                GridLength length => length,
                _ => new GridLength(1, GridUnitType.Star)
            };
        }

        return new GridLength(0);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return [];
    }


    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is bool bln && bln != IsReversed)
        {
            return parameter switch
            {
                double d => new GridLength(d),
                GridLength length => length,
                _ => new GridLength(1, GridUnitType.Star)
            };
        }

        return new GridLength(0);
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}